func reverseWords(s string) string {
    s = trim([]rune(s))
    var chars = []rune(s)
    reverse(chars, 0, len(chars) - 1)
    reverseEachWord(chars)
    return string(chars)
}

func reverseEachWord(chars []rune) {
    n := len(chars)
    slow, fast := 0, 0

    for fast < n {
        for fast < n && chars[fast] != ' ' {
            fast++
        }
        reverse(chars, slow, fast-1)
        fast++
        slow = fast
    }
}

func reverse(chars []rune, start, end int) {
    for start < end {
        chars[start], chars[end] = chars[end], chars[start]
        start++
        end--
    }
}

// 删除字符串中所有的空字符，但是单词之间需要一个空字符隔开
// 时间复杂度：O(n)
// 空间复杂度：O(1)，原地删除空字符
func trim(chars []rune) string {
    n := len(chars)
    slow, fast := 0, 0

    for fast < n {
        if chars[fast] != ' ' || (fast >= 1 && chars[fast - 1] != ' ') {
            chars[slow] = chars[fast]
            slow++
        }
        fast++
    }

    if slow >= 1 && chars[slow - 1] == ' ' {
        slow--
    }

    return string(chars[0:slow])
}